package com.smartstores.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.smartstores.R;
import com.smartstores.mundo.Producto;

public class CustomListAdapter extends BaseAdapter {

	private List<Producto> list;

	private List<Producto> checked;

	private Context ctx;

	public CustomListAdapter(Context ctx, List<Producto> list) {
		this.ctx = ctx;
		this.list = list;

		checked = new ArrayList<Producto>();
	}

	@Override
	public int getCount() {
		return list != null ? list.size() : 0;
	}

	@Override
	public Producto getItem(int pos) {
		return list.get(pos);
	}

	@Override
	public long getItemId(int pos) {
		return pos;
	}

	@Override
	public View getView(final int pos, View cv, ViewGroup parent) {

		LinearLayout row = null;

		if (cv == null) {
			row = (LinearLayout) LayoutInflater.from(ctx).inflate(
					R.layout.carrito_row, parent, false);
		} else {
			row = (LinearLayout) cv;
		}

		TextView text = (TextView) row.findViewById(R.id.text_carrito);
		text.setText(list.get(pos).getNombre() + " : $"
				+ list.get(pos).getPrecio());

		CheckBox check = (CheckBox) row.findViewById(R.id.check_carrito);
		
		if(checked.isEmpty()){
			check.setChecked(false);
		}
		
		check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					checked.add(list.get(pos));
				} else {
					checked.remove(list.get(pos));
				}
			}
		});
		
		return row;
	}

	public List<Producto> getItemsChecked() {
		return checked;
	}

	public void uncheckAll() {
		checked.clear();
		notifyDataSetChanged();
	}
}
